package com.xiaoxin.framework.datasource;

import com.alibaba.druid.pool.DruidDataSource;
//import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.xiaoxin.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.lang.reflect.Method;

/**
 * 数据源切换处理
 *
 * @author zhangxx
 */
public class DynamicDataSourceContextHolder
{
    public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);

    /**
     * 使用ThreadLocal维护变量，ThreadLocal为每个使用该变量的线程提供独立的变量副本，
     *  所以每一个线程都可以独立地改变自己的副本，而不会影响其它线程所对应的副本。
     */
    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();

    /**
     * 设置数据源的变量
     */
    public static void setDataSourceType(String dsType)
    {
        log.info("切换到{}数据源", dsType);
        CONTEXT_HOLDER.set(dsType);

        //切换分页插件方言
        //setDialect();
    }

    /**
     * 获得数据源的变量
     */
    public static String getDataSourceType()
    {
        return CONTEXT_HOLDER.get();
    }

    /**
     * 清空数据源变量
     */
    public static void clearDataSourceType()
    {
        CONTEXT_HOLDER.remove();
        //切换分页插件方言
        //setDialect();
    }

/*    private static void setDialect(){
        //切换分页插件方言
        try {
            DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
            Method determineTargetDataSourceMethod = BeanUtils.findDeclaredMethod(AbstractRoutingDataSource.class, "determineTargetDataSource");
            determineTargetDataSourceMethod.setAccessible(true);
            DruidDataSource dateSource = (DruidDataSource) determineTargetDataSourceMethod.invoke(dynamicDataSource);
            String type = dateSource.getDbType();
            //切换分页方言(新版)
            //SpringUtils.getBean(PaginationInterceptor.class).setDialectType(type);//旧版
            SpringUtils.getBean(PaginationInnerInterceptor.class).setDbType(DbType.getDbType(type));
        } catch (Exception e) {
            log.error("Dialect Switching Failed!", e);
        }
    }*/
}
